package com.project.demo.parser;

import com.google.common.base.Strings;
import com.je.core.service.MetaService;
import com.je.core.service.PCDynaServiceTemplate;
import com.je.core.util.*;
import com.je.core.util.bean.BeanUtils;
import com.je.core.util.bean.DynaBean;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.model.EndUser;
import com.je.thrid.parser.AbstractDynaBeanImportParser;
import com.je.thrid.vo.ParseVo;
import net.sf.json.JSONObject;
import org.springframework.security.providers.encoding.Md5PasswordEncoder;

import java.util.Arrays;
import java.util.List;

/**
 * @program: je-platform
 * @author: LIULJ
 * @create: 2020/7/26
 * @description:
 */
public class EndUserImportParser extends AbstractDynaBeanImportParser {

    @Override
    public ParseVo parse(DynaBean user, JSONObject customParameters) {
        MetaService metaService = SpringContextHolder.getBean(MetaService.class);
        user.setStr(BeanUtils.KEY_TABLE_CODE, "JE_CORE_ENDUSER");
        String userCode = user.getStr("USERCODE");
        // 处理登录名重复
        int count = metaService.select("JE_CORE_ENDUSER", ConditionsWrapper.builder().eq("USERCODE", userCode)).size();
        if (count > 0) {
            return new ParseVo(null, false);
        }
        user.setStr("BACKUSERCODE", userCode);
        user.setStr("USERCODE", userCode);
        String birthday = user.getStr("BIRTHDAY");
        if (Strings.isNullOrEmpty(birthday)) {
            birthday = DateUtils.formatDate(DateUtils.getDate(birthday, DateUtils.DAFAULT_DATE_FORMAT),
                DateUtils.DAFAULT_DATE_FORMAT);
            // 生日
            user.setStr("BIRTHDAY", birthday);
        }
        // 邮箱
        user.setStr("COMPANYEMAIL", user.getStr("COMPANYEMAIL"));
        // 固话
        String tel = user.getStr("PHONE");
        user.setStr("ZUOJI", tel);
        // 认证手机号
        String phone = user.getStr("PHONE");
        user.setStr("IDENTPHONE", phone);
        // 手机号
        user.setStr("PHONE", phone);
        // 性别
        if (!Strings.isNullOrEmpty(user.getStr("GENDER"))) {
            DynaBean genderInfos = metaService.selectOne("JE_CORE_DICTIONARYITEM",
                ConditionsWrapper.builder().eq("DICTIONARYITEM_ITEMNAME", user.getStr("GENDER")).apply(
                    " AND DICTIONARYITEM_DICTIONARY_ID=(select JE_CORE_DICTIONARY_ID from JE_CORE_DICTIONARY WHERE DICTIONARY_DDCODE='JE_SEX')"),
                "DICTIONARYITEM_ITEMCODE");
            user.setStr("GENDER", genderInfos.getStr("DICTIONARYITEM_ITEMCODE"));
        } else {
            user.setStr("GENDER", "MAN");
        }
        // 密码
        Md5PasswordEncoder md5 = new Md5PasswordEncoder();
        String defaulePassWord =
            md5.encodePassword(StringUtil.getDefaultValue(WebUtils.getSysVar("JE_SYS_PASSWORD"), "123456"), null);
        user.set("PASSWORD", defaulePassWord);
        //
        user.set("ISMANAGER", "0");
        buildUserDeptInfo(user, metaService);
        // buildUserRoleInfo(user, metaService);
        // true 插入 false不插入
        return new ParseVo(user, false);
    }

    /**
     * 部门信息
     *
     * @param user
     */
    private void buildUserDeptInfo(DynaBean user, MetaService metaService) {
        String deptName = user.getStr("DEPTNAME");
        String[] deptAllNames = deptName.split(";");
        for(String deptAllName : deptAllNames){
            user.setStr("USERID", JEUUID.uuid());
            String[] deptNames = deptAllName.split("/");
            deptName = deptNames[deptNames.length - 1];
            DynaBean dept = null;
            List<DynaBean> depts =
                    metaService.select("JE_CORE_DEPARTMENT", ConditionsWrapper.builder().eq("DEPTNAME", deptName));
            if (depts.size() == 1) {
                dept = depts.get(0);
            } else if (depts.size() > 1) {
                String deptId = "";
                String parentDeptId = "";
                int i = 0;
                for (String str : deptNames) {
                    DynaBean addDept = new DynaBean();
                    if (i == 0) {
                        addDept =
                                metaService.selectOne("JE_CORE_DEPARTMENT", ConditionsWrapper.builder().eq("DEPTNAME", str));
                        parentDeptId = addDept.getStr("DEPTID");
                        deptId = addDept.getStr("DEPTID");
                    } else {
                        parentDeptId = metaService
                                .selectOne("JE_CORE_DEPARTMENT",
                                        ConditionsWrapper.builder().eq("DEPTNAME", str).eq("PARENT", parentDeptId))
                                .getStr("DEPTID");
                        deptId = parentDeptId;
                    }
                    i++;
                }
                dept = metaService.selectOne("JE_CORE_DEPARTMENT", ConditionsWrapper.builder().eq("DEPTID", deptId));
            }
            if (dept == null) {
                dept = metaService.selectOne("JE_CORE_DEPARTMENT", ConditionsWrapper.builder().eq("DEPTNAME", "系统管理部"));
            }
            user.setStr("DEPTCODE", dept.getStr("DEPTCODE"));
            user.setStr("DEPTNAME", dept.getStr("DEPTNAME"));
            user.setStr("DEPTID", dept.getStr("DEPTID"));
            user.setStr("DEPTORDERINDEX", dept.getStr("TREEORDERINDEX"));
            buildUserCreateInfo(user);
            metaService.insert(user);
        }
    }

    /**
     * 角色信息
     *
     * @param user
     */
    private void buildUserRoleInfo(DynaBean user, MetaService metaService) {
        String roleNames = user.getStr("ROLENAMES");
        List<String> roleNamesList = Arrays.asList(roleNames.split(","));
        List<DynaBean> role = metaService.select("JE_CORE_ROLE",
            ConditionsWrapper.builder().in("ROLENAME", roleNamesList).eq("ROLETYPE", "ROLE").groupBy("ROLENAME"));
        if (role.size() == 0) {
            throw new RuntimeException(roleNames + "角色没有找到数据异常！");
        }
        StringBuffer roleIds = new StringBuffer();
        StringBuffer roleNamesStr = new StringBuffer();
        StringBuffer roleCodes = new StringBuffer();
        for (DynaBean roleDynaBean : role) {
            DynaBean roleUser = new DynaBean("JE_CORE_ROLE_USER", true);
            roleUser.setStr("USERID", user.getStr("USERID"));
            roleUser.setStr("ROLEID", roleDynaBean.getStr("ROLEID"));
            metaService.insert(roleUser);
            if (Strings.isNullOrEmpty(roleIds.toString())) {
                roleIds.append(roleDynaBean.getStr("ROLEID"));
                roleNamesStr.append(roleDynaBean.getStr("ROLENAME"));
                roleCodes.append(roleDynaBean.getStr("ROLECODE"));
            } else {
                roleIds.append("," + roleDynaBean.getStr("ROLEID"));
                roleNamesStr.append("," + roleDynaBean.getStr("ROLENAME"));
                roleCodes.append("," + roleDynaBean.getStr("ROLECODE"));
            }
        }
        // 角色编码
        user.setStr("ROLECODES", roleCodes.toString());
        // 角色主键
        user.setStr("ROLEIDS", roleIds.toString());
        // 角色名称
        user.setStr("ROLENAMES", roleNamesStr.toString());
        metaService.update(user);
    }

    /**
     * 基础信息
     *
     * @param user
     */
    private void buildUserCreateInfo(DynaBean user) {
        user.setStr("ISSYSUSER", "1");
        user.setStr("FLAG", "1");
        String ORDERINDEX = user.getStr("DISPLAY_ORDER");
        user.set("USERORDER", ORDERINDEX);
        user.setStr("INITPASSWORD", "1");
        user.setStr("SENTRYCODES", "");
        user.setStr("MONITORDEPTCODE", "");
        user.setStr("MENUTYPE", "");
        user.setStr("LOGINLOCKED", "0");
        user.setStr("VALID", "1");
        user.setStr("STATUS", "1");
        PCDynaServiceTemplate pcDynaServiceTemplate = SpringContextHolder.getBean(PCDynaServiceTemplate.class);
        pcDynaServiceTemplate.buildModelCreateInfo(user);
        EndUser endUser = SecurityUserHolder.getCurrentUser();
        user.setStr("CREATEORG", endUser.getDeptCode());
        user.setStr("CREATEORGNAME", endUser.getDeptName());
        user.setStr("CREATETIME", user.getStr("SY_CREATETIME"));
        user.setStr("CREATEUSER", endUser.getUserCode());
        user.setStr("CREATEUSERNAME", endUser.getUsername());
        user.setStr("MODIFYUSER", endUser.getUserCode());
        user.setStr("MODIFYUSERNAME", endUser.getUsername());
        user.setStr("JTGSMC", endUser.getJtgsMc());
        user.setStr("JTGSDM", endUser.getJtgsDm());
        user.setStr("JTGSID", endUser.getJtgsId());
        user.setStr("GSBMID", endUser.getGsbmId());
        user.setStr("ZHID", endUser.getZhId());
        user.setStr("ZHMC", endUser.getZhMc());
    }

}
